package com.centriole.common.utils;

import com.centriole.common.entity.TokenEntity;
import net.sf.json.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @Author: zhangjj
 * @Description: paas 平台 token 工具类
 * @Date: Created in 2018/5/9 0009 10:10
 * @Modified:
 */
public class TokenUtil {
    public static void main(String[] args) {
        TokenEntity token = new TokenEntity();
        token.setUserName("jack");
        token.setTime(new Date());
        token.setSignature("A");

        String str = encoderToken(token);
        System.out.println("加密后:" + str);

        TokenEntity te = decoderToken(str);

        System.out.println("ab");
    }

    /**
     * @Author: zhangjj
     * @Description: 将 token 实例对象加密
     * @Date: 13:30 2018/5/9 0009
     * @Modified:
     * @Param: token
     * @Return: String 加密后的字符串
     */
    public static String encoderToken(TokenEntity token) {
        // 判断对象是否为空
        if (token == null) {
            return "not null";
        }

        Field[] fields = token.getClass().getDeclaredFields();
        JSONObject json = new JSONObject();
        for (int i = 0; i < fields.length; i++) {
            try {
                fields[i].setAccessible(true);
                json.put(fields[i].getName(), fields[i].get(token).toString());
            } catch (NullPointerException e) {
                json.put(fields[i].getName(), null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        BASE64Encoder encoder = new BASE64Encoder();

        byte[] textByte = new byte[0];
        try {
            textByte = json.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String encodedText = encoder.encode(textByte);

        return encodedText;
    }

    /**
     * @Author: zhangjj
     * @Description: 解密 token
     * @Date: 13:31 2018/5/9 0009
     * @Modified:
     * @Param: str 一个加密的 token 字符串
     * @Return: TokenEntity
     */
    public static TokenEntity decoderToken(String str) {
        BASE64Decoder decoder = new BASE64Decoder();
        TokenEntity tokenEntity = new TokenEntity();
        try {
            str = new String(decoder.decodeBuffer(str));

            tokenEntity = (TokenEntity) jsonToEntity(str, tokenEntity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tokenEntity;
    }

    /**
     * @Author: zhangjj
     * @Description: 将一个 json 字符串转成实体对象
     * @Date: 13:32 2018/5/9 0009
     * @Modified:
     * @Param: str 一个 json 格式的字符串
     * @Param: object
     */
    public static Object jsonToEntity(String str, Object object) {
        Field[] fields = object.getClass().getDeclaredFields();

        JSONObject json = JSONObject.fromObject(str);

        for (int i = 0; i < fields.length; i++) {
            fields[i].setAccessible(true);
            try {
                System.out.println(fields[i].getName() + " ========== " + fields[i].getType());
                // 处理int类型
                if (fields[i].getType().equals(int.class) || fields[i].getType().equals(Integer.class)) {
                    fields[i].set(object, Integer.parseInt(json.get(fields[i].getName()).toString()));
                }

                // 处理时间
                if (fields[i].getType().equals(Date.class)) {
                    SimpleDateFormat sf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                    try {
//                        System.out.println(json.get(fields[i].getName()).toString());

                        Date date = sf.parse(json.get(fields[i].getName()).toString());
                        fields[i].set(object, date);
                    } catch (NullPointerException npe) {
                        fields[i].set(object, null);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }

                // 处理字符串
                if (fields[i].getType().equals(String.class)) {
                    fields[i].set(object, json.get(fields[i].getName()));

                }

            } catch (NullPointerException npe) {
                try {
                    // 处理int类型
                    if (fields[i].getType().equals(int.class) || fields[i].getType().equals(Integer.class)) {
                        fields[i].set(object, 0);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return object;
    }
}
